--[[
Functions.inc
Contains basic functions for use in other scripts.

-------------------------
Changelog:
1.1
-Added getNumberofWords and removeAllSymbols

1.0
-Contains basically all the root functions used by my previous scripts.
]]

--Constants--
_,bot_name = VH:GetConfig("config", "hub_security")
-------------

--SendMessageToHub
--Sends a message to the entire hub from a user.  If "from" parameter is
--neglected, the message will be sent from hub_security.
function SendMessageToHub(data, from)
	if (from == nil) then
		--Send it from hub security
		from = bot_name
	end
	return VH:SendDataToAll("<"..from.."> "..data.."|",0,10)
end

--SendMessageToUser
--Sends a message to a specific user in mainchat.  If "nick" parameter is
--neglected, the message will be sent to the whole hub.  If the "from" parameter
--is neglected, the message will be sent from hub_security.
function SendMessageToUser(data, nick, from)
	if (from == nil) then
		--Send it from hub security.
		from = bot_name
	end
	
	if (nick == nil) then
		--Send it to the whole hub.
		return VH:SendDataToAll("<"..from.."> "..data.."|",0,10)
	end
	
	return VH:SendDataToUser("<"..from.."> "..data.."|", nick)
end

function SendPrivateMessageToUser(user, data, from)
    return VH:SendDataToUser("$To: "..user.." From: "..from.." $<"..from.."> "..data.."|", user);
end

function DisplayHelpMessage(cmdname, cmd, msg, nick)
    SendMessageToUser("        ."..cmdname.." "..cmd, nick, bot_name)
    SendMessageToUser("        "..msg, nick, bot_name)
end

function UserClass(nick)
	res, class = VH:GetUserClass(nick)
	if res and class then return class else return 0 end
end

function UserIsOnline(nick)
	result, sIP = VH:GetUserIP(nick)
	if (string.len(sIP) < 7) then
		return false
	else
		return true
	end
end

function UserIP(nick)
	result, sIP = VH:GetUserIP(nick)
	if (string.len(sIP) < 7) then
		return 0
	else
		return sIP
	end
end

function SendEmoteToHub(data, from)
	result, err = VH:SendDataToAll("<"..from.."> ".."/me "..data.."|",0,10)
	return 1
end

function KickAllUsersWithIP(ip, reason)
	_,nicklist = VH:GetNickList()
	nicklist = string.sub(nicklist, 11)
	local flag = false
	for names in string.gmatch(nicklist, "([^%$]+)%$%$") do
		if (ip == UserIP(names)) then
			if (flag == false) then
				VH:KickUser(security, names, reason)
				flag = true
			else
				VH:CloseConnection(names)
			end
		end
	end
end

function getNumberOfWords(s)
	local wc = 0
	for _ in string.gmatch(s, "%a+") do
		wc = wc + 1
	end
	return wc
end

function removeAllSymbols(s)
	local outstring = ""
	for l in string.gmatch(s, "%w") do
		outstring = outstring + l
	end
	return outstring
end

function pluralise(s, i)
	if (i ~= 1) then
		if (string.sub(s, string.len(s)) == "s") then
			return s.."es"
		else
			return s.."s"
		end
	else
		return s
	end
end
